<?php

/**
 * class common
 * provides common functions to be used
 */
class TaxonomyHelper {
  /**
   * @param tid
   *   Term ID
   * @param child_count
   *   TRUE - Also count all nodes in child terms (if they exists) - Default
   *   FALSE - Count only nodes related to Term ID
   */
  public static function term_nodes_count($tid, $child_count = FALSE) {
    $tids = array($tid);

    if ($child_count) {
      $tids = array_merge($tids, self::term_get_children_ids($tid));
    }

    global $language;
    $langs = array($language->language);
    $langs[] = 'und';

    $query = db_select('field_data_field_board', 't');
    $query->condition('t.field_board_tid', $tids, 'IN');
    $query->condition('t.entity_type', 'node');
    $query->condition('t.bundle', 'nip');
    $query->condition('t.deleted', 0);

    $count = $query->countQuery()->execute()->fetchField();
    return  $count;
  }

  /**
   * Retrieve ids of term children .
   *
   * @param $tid
   *   The term's ID.
   * @param $tids
   *   An array where ids of term children will be added
   */
  public static function term_get_children_ids($tid) {
    $children = taxonomy_get_children($tid);
    $tids=array();

    if (!empty($children)) {
      foreach($children as $child) {
        $tids[] = $child->tid;
        $tids = array_merge($tids, self::term_get_children_ids($child->tid));
      }
    }
    return $tids;
  }

  /**
   * helper function for getting term name by tid
   * @param $tid
   * @param int $vid
   * @return mixed
   */
  public static function taxonomy_get_term_name($tid, $vid = 1) {
    $term_names = &drupal_static(__FUNCTION__);

    if (!$term_names) {
      $term_names = array();
    }
    elseif (isset($term_names[$tid])) {
      return $term_names[$tid];
    }

    $term_name = db_query('SELECT name FROM {taxonomy_term_data} WHERE tid = :tid AND vid = :vid', array(':tid' => $tid, ':vid' => $vid))->fetchField();
    if ($term_name) {
      $term_names[$tid] = $term_name;
    }

    return $term_name;
  }
}
